using UnityEngine;
using System.Collections;

public class MouseOrbitPro : MonoBehaviour
{
	public Transform Target;
	public float Distance = 10F;
	
	public float XSpeed = 250F;
	public float YSpeed = 120F;
	
	public int YMinLimit = -20;
	public int YMaxLimit = 80;
	
	private float _x = 0F;
	private float _y = 0F;
	
	void Start ()
	{
	    Vector3 angles = transform.eulerAngles;
	    _x = angles.y;
	    _y = angles.x;
	
		// Make the rigid body not change rotation
	   	if (rigidbody)
			rigidbody.freezeRotation = true;
	}
	
	void LateUpdate ()
	{
	    if (Target)
	    {
	    	if(Screen.lockCursor)
	    	{
	        	_x += Input.GetAxis("Mouse X") * XSpeed * 0.02F;
	       		_y -= Input.GetAxis("Mouse Y") * YSpeed * 0.02F;
	 		}
	 		
	 		_y = ClampAngle(_y, YMinLimit, YMaxLimit);
	 		       
	        Quaternion rotation = Quaternion.Euler(_y, _x, 0);
	        Vector3 position = rotation * new Vector3(0, 0, -Distance) + Target.position;
	        
	        transform.rotation = rotation;
	        transform.position = position;
	    }
	}
	
	static float ClampAngle (float angle, float min, float max)
	{
		if (angle < -360)
			angle += 360;
		if (angle > 360)
			angle -= 360;
		return Mathf.Clamp (angle, min, max);
	}
}

